﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;
using System.IO;

namespace DSS_Simplex
{
    public partial class Form1 : Form
    {
        //printing
        StringFormat strFormat; //Used to format the grid rows.
        ArrayList arrColumnLefts = new ArrayList();//Used to save left coordinates of columns
        ArrayList arrColumnWidths = new ArrayList();//Used to save column widths
        int iCellHeight = 0; //Used to get/set the datagridview cell height
        int iTotalWidth = 0; //
        int iRow = 0;//Used as counter
        bool bFirstPage = false; //Used to check whether we are printing first page
        bool bNewPage = false;// Used to check whether we are printing a new page
        int iHeaderHeight = 0; //Used for the header height

        public Form1()
        {
            InitializeComponent();
            //DG color
            dataGridView4.DefaultCellStyle.SelectionBackColor = Color.PeachPuff;
            dataGridView4.DefaultCellStyle.SelectionForeColor = Color.Black;
            dataGridView2.DefaultCellStyle.SelectionBackColor = Color.PeachPuff;
            dataGridView2.DefaultCellStyle.SelectionForeColor = Color.Black;
            dataGridView1.DefaultCellStyle.SelectionBackColor = Color.PeachPuff;
            dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;
            dataGridView4.Columns[0].ReadOnly = true;
            dataGridView4.Columns[0].DefaultCellStyle.BackColor = Color.RoyalBlue;
            toolStripDropDownButton2.Enabled = false;
            toolStripButton2.Enabled = false;
        }

        private void OpenExistingVariable(object sender, EventArgs e)
        {
            Form2.temporerDG(dataGridView1);
            Form2 fr = new Form2();
            fr.Focus();
            fr.ShowDialog();

        }

        private void OpenExistingConstraint(object sender, EventArgs e)
        {
            FormConst.temporerDG(dataGridView2);
            FormConst fc = new FormConst();
            fc.Focus();
            fc.ShowDialog();
        }

        private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //akses dg2 ke dg3
            try
            {
                for (int x = 0; x < dataGridView2.Rows.Count; x++)
                {
                    dataGridView4.RowCount = dataGridView2.Rows.Count;
                    dataGridView4.Rows[x].Cells[0].Value = dataGridView2.Rows[x].Cells[0].Value + "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //akses dg1 ke dg4
            try
            {
                for (int x = 0; x < dataGridView1.Rows.Count - 1; x++)
                {
                    dataGridView4.ColumnCount = dataGridView1.Rows.Count;
                    dataGridView4.Columns[x + 1].Name = dataGridView1.Rows[x].Cells[0].Value + " ";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ApplicationRun(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.EndEdit();
                dataGridView2.EndEdit();
                dataGridView4.EndEdit();
                dataGridView1.Enabled = false;
                dataGridView2.Enabled = false;
                dataGridView4.Enabled = false;
                dataGridView1.ForeColor = Color.Silver;
                dataGridView2.ForeColor = Color.Silver;
                dataGridView4.ForeColor = Color.Silver;
                dataGridView1.BackgroundColor = Color.LightGray;
                dataGridView2.BackgroundColor = Color.LightGray;
                dataGridView4.BackgroundColor = Color.LightGray;

                dataGridView4.DefaultCellStyle.SelectionBackColor = Color.White;
                dataGridView4.DefaultCellStyle.SelectionForeColor = Color.Silver;
                dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White;
                dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Silver;
                dataGridView2.DefaultCellStyle.SelectionBackColor = Color.White;
                dataGridView2.DefaultCellStyle.SelectionForeColor = Color.Silver;
                dataGridView4.Columns[0].DefaultCellStyle.SelectionBackColor = Color.RoyalBlue;
                dataGridView4.Columns[0].DefaultCellStyle.SelectionForeColor = Color.Silver;

                if (radioButton1.Checked == true)
                {
                    Mesin.RunComputation(true, dataGridView1, dataGridView2, dataGridView4); 
                    toolStripDropDownButton2.Enabled = true;
                    toolStripButton1.Enabled = false;
                    toolStripButton2.Enabled = true;
                    optimalSolutionReportToolStripMenuItem.ShowDropDown();
                    toolStripDropDownButton2.ShowDropDown();
                    
                }
                if (radioButton2.Checked == true)
                {
                    Mesin.RunComputation(false, dataGridView1, dataGridView2, dataGridView4);
                    toolStripDropDownButton2.Enabled = true;
                    toolStripButton1.Enabled = false;
                    toolStripButton2.Enabled = true;
                    optimalSolutionReportToolStripMenuItem.ShowDropDown();
                    toolStripDropDownButton2.ShowDropDown();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Exit(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void SaveToDb(object sender, EventArgs e)
        {
            try
            {
                FileCmd.TemporarySaveDGV(dataGridView1, dataGridView2, dataGridView4);
                SaveAs saveAs = new SaveAs();
                saveAs.Focus();
                saveAs.ShowDialog();

            }
            //FileCmd.SaveAs(dataGridView1, dataGridView2, dataGridView4);
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        //open file from spreadsheet by selecting data
        private void OpenXlsVar(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Aplikasi akan membuka dokumen spreadsheet Anda. Selanjutnya silakan copy tabel dari file tersebut,\nlalu paste-kan pada grid. Lanjut?", "Open File", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (result == DialogResult.Yes)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Excel files (*.xls;*.xlsx)|*.xls;*.xlsx|All files (*.*)|*.*";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (ofd.CheckFileExists)
                        {
                            (new WebBrowser()).Navigate(ofd.FileName, false);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message);
                    }
                }
            }
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete)
            {
                foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
                {
                    cell.Value = null;
                }
                
            }
            if (e.Control && e.KeyCode == Keys.C)
            {
                DataObject d = dataGridView1.GetClipboardContent();
                Clipboard.SetDataObject(d);
                e.Handled = true;
            }
            else if (e.Control && e.KeyCode == Keys.V)
            {
                /*string[] cb = Clipboard.GetText(TextDataFormat.Text).Split(new string[1] { "\r\n" }, StringSplitOptions.None);
                string[] cells = cb[0].Split(new string[1] { "\t" }, StringSplitOptions.None);
                if (cells.Length == 5)
                {
                    dataGridView1.Rows.Clear();
                    for (int i = 0; i < cb.Length; i++)
                        dataGridView1.Rows.Add(cb[i].Split(new string[1] { "\t" }, StringSplitOptions.None));
                }
                else
                    MessageBox.Show("Jumlah kolom salah!");*/
                DataObject o = (DataObject)Clipboard.GetDataObject();

                if (o.GetDataPresent(DataFormats.Text))
                {

                    int rowOfInterest = dataGridView1.CurrentCell.RowIndex;
                    string[] selectedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n");

                    if (selectedRows == null || selectedRows.Length == 0)
                        return;

                    foreach (string row in selectedRows)
                    {
                        if (rowOfInterest >= dataGridView1.Rows.Count)
                            break;

                        try
                        {
                            string[] data = Regex.Split(row, "\t");
                            int col = dataGridView1.CurrentCell.ColumnIndex;
                            dataGridView1.Rows.Add();
                            
                            foreach (string ob in data)
                            {

                                if (col >= dataGridView1.Columns.Count)
                                    break;
                                if (ob != null)
                                    dataGridView1[col, rowOfInterest].Value = Convert.ChangeType(ob, dataGridView1[col, rowOfInterest].ValueType);
                                col++;
                            }
                        }
                        catch (Exception exc)
                        {
                            MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        rowOfInterest++;
                    }
                }
            }
        }
        private void OpenXlsConst(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Aplikasi akan membuka dokumen spreadsheet Anda. Selanjutnya silakan copy tabel dari file tersebut,\nlalu paste-kan pada grid. Lanjut?", "Open File", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (result == DialogResult.Yes)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Excel files (*.xls;*.xlsx)|*.xls;*.xlsx|All files (*.*)|*.*";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (ofd.CheckFileExists)
                        {
                            (new WebBrowser()).Navigate(ofd.FileName, false);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message);
                    }
                }
            }

        }
        private void dataGridView2_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete)
            {
                foreach (DataGridViewCell cell in dataGridView2.SelectedCells)
                {
                    cell.Value = null;
                }
            }
            if (e.Control && e.KeyCode == Keys.C)
            {
                DataObject d = dataGridView2.GetClipboardContent();
                Clipboard.SetDataObject(d);
                e.Handled = true;
            }
            else if (e.Control && e.KeyCode == Keys.V)
            {
                DataObject o = (DataObject)Clipboard.GetDataObject();

                if (o.GetDataPresent(DataFormats.Text))
                {

                    int rowOfInterest = dataGridView2.CurrentCell.RowIndex;
                    string[] selectedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n");

                    if (selectedRows == null || selectedRows.Length == 0)
                        return;

                    foreach (string row in selectedRows)
                    {
                        if (rowOfInterest >= dataGridView2.Rows.Count)
                            break;

                        try
                        {
                            string[] data = Regex.Split(row, "\t");
                            int col = dataGridView2.CurrentCell.ColumnIndex;
                            //dataGridView2.Rows.Add();
                            foreach (string ob in data)
                            {
                                
                                if (col >= dataGridView2.Columns.Count)
                                    break;
                                if (ob != null)
                                    dataGridView2[col, rowOfInterest].Value = Convert.ChangeType(ob, dataGridView2[col, rowOfInterest].ValueType);
                                col++;
                            }
                        }
                        catch (Exception exc)
                        {
                            MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        rowOfInterest++;
                    }
                }
            }
        }
        private void databaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void IterationReport(object sender, EventArgs e)
        {
            Report1 report1 = new Report1();
            report1.ShowDialog();
        }
        //additional
        private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            //akses dg2 ke dg3
            try
            {
                for (int x = 0; x < dataGridView2.Rows.Count; x++)
                {
                    dataGridView4.RowCount = dataGridView2.Rows.Count;
                    dataGridView4.Rows[x].Cells[0].Value = dataGridView2.Rows[x].Cells[0].Value + "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            //akses dg1 ke dg4
            try
            {
                for (int x = 0; x < dataGridView1.Rows.Count - 1; x++)
                {
                    dataGridView4.ColumnCount = dataGridView1.Rows.Count;
                    dataGridView4.Columns[x + 1].Name = dataGridView1.Rows[x].Cells[0].Value + " ";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SensitivityReport(object sender, EventArgs e)
        {
            Sensitivity_Report SenRep = new Sensitivity_Report();
            SenRep.ShowDialog();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void OptimalSolutionReport(object sender, EventArgs e)
        {
            
        }

        private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                //isi DGV
                #region isi DGV

                Mesin.Variable_Analysis();
                string[] Var_Analysis_Max = Mesin.Var_Analysis_Max;
                string[] Var_Analysis_Min = Mesin.Var_Analysis_Min;
                string[] NonBasisVar = Mesin.ArrNonBasisVar;
                
                List<double[,]> list = Mesin.ListRepValue;
                int var = dataGridView1.RowCount - 1;

                DGPrintPrev.RowCount = var;
                DGPrintPrev.ColumnCount = 6;
                //dss value

                List<string[]> ListBasisVar = Mesin.ListBasisVar;
                
                int jml = list.ElementAt(0).GetLength(0) - 1;
                double[] Var_Dss_print = new double[jml];
                for (int i = 0; i < jml; i++)
                {
                    Var_Dss_print[i] = 0;

                }
                for (int x = 0; x < jml; x++)
                {
                    for (int y = 0; y < jml; y++)
                    {
                        //jika sama
                        if (ListBasisVar.ElementAt(ListBasisVar.Count - 1)[x] == NonBasisVar[y])
                        {
                            Var_Dss_print[y] = list.ElementAt(list.Count - 1)[x + 1, 0];

                        }
                    }
                }
                
                //nama var
                for (int i = 0; i < var; i++)
                {
                    DGPrintPrev.Rows[i].Cells[0].Value = NonBasisVar[i];
                }
                //jml coef
                for (int i = 0; i < var; i++)
                {
                    DGPrintPrev.Rows[i].Cells[1].Value = Var_Dss_print[i];
                }
                //jml sekarang
                for (int i = 0; i < var; i++)
                {
                    DGPrintPrev.Rows[i].Cells[2].Value = dataGridView1.Rows[i].Cells[1].Value;
                }
                //koef*jml
                for (int i = 0; i < var; i++)
                {
                    DGPrintPrev.Rows[i].Cells[5].Value = Math.Round(Var_Dss_print[i] * double.Parse(dataGridView1.Rows[i].Cells[1].Value +""),4);
                }
                //jml minimal
                for (int i = 0; i < var; i++)
                {
                    if (Var_Analysis_Min[i] == "Infinity")
                    {
                        DGPrintPrev.Rows[i].Cells[3].Value = "Infinity";
                    }
                    else
                    {
                        DGPrintPrev.Rows[i].Cells[3].Value = Math.Round(double.Parse(dataGridView1.Rows[i].Cells[1].Value + "") + double.Parse(Var_Analysis_Min[i]), 3);
                    }
                }
                //jml maksimal
                for (int i = 0; i < var; i++)
                {
                    if (Var_Analysis_Max[i] == "Infinity")
                    {
                        DGPrintPrev.Rows[i].Cells[4].Value = "Infinity";
                    }
                    else
                    {
                        DGPrintPrev.Rows[i].Cells[4].Value = Math.Round(double.Parse(dataGridView1.Rows[i].Cells[1].Value +"") + double.Parse(Var_Analysis_Max[i]), 3);
                    }
                }
                #endregion

                #region beginprint

                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Near;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iRow = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;
                foreach (DataGridViewColumn dgvGridCol in DGPrintPrev.Columns)
                {
                    iTotalWidth += dgvGridCol.Width;
                }

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                //Set the left margin
                int iLeftMargin = e.MarginBounds.Left;
                //Set the top margin
                int iTopMargin = e.MarginBounds.Top;
                //Whether more pages have to print or not
                bool bMorePagesToPrint = false;
                int iTmpWidth = 0;
                bool StopReading = false;

                
                double total = 0;
                for (int i = 0; i < DGPrintPrev.RowCount; i++ )
                {
                    total = total + (double.Parse(DGPrintPrev.Rows[i].Cells[5].Value + ""));
                }

                if (bFirstPage)
                {
                    foreach (DataGridViewColumn GridCol in DGPrintPrev.Columns)
                    {
                        
                        iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                                           (double)iTotalWidth * (double)iTotalWidth *
                                           ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                        iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                                    GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                        // Save width and height of headres
                        arrColumnLefts.Add(iLeftMargin);
                        arrColumnWidths.Add(iTmpWidth);
                        iLeftMargin += iTmpWidth;
                    }
                }
                //Loop till all the grid rows not get printed
                while (iRow <= DGPrintPrev.Rows.Count - 1)
                {
                    DataGridViewRow GridRow = DGPrintPrev.Rows[iRow];
                    //Set the cell height
                    iCellHeight = GridRow.Height + 5;
                    int iCount = 0;
                    //Check whether the current page settings allo more rows to print
                    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                    {
                        bNewPage = true;
                        bFirstPage = false;
                        bMorePagesToPrint = true;
                        break;
                    }
                    else
                    {
                        if (bNewPage)
                        {
                            e.Graphics.DrawString("Laporan Optimal", new Font(DGPrintPrev.Font, FontStyle.Bold),
                                    Brushes.Black, e.MarginBounds.Left + 250, e.MarginBounds.Top -
                                    e.Graphics.MeasureString("Laporan Optimal", new Font(DGPrintPrev.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Height - 10);
                            //Draw Header
                            e.Graphics.DrawString("", new Font(DGPrintPrev.Font, FontStyle.Bold),
                                    Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
                                    e.Graphics.MeasureString("", new Font(DGPrintPrev.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Height - e.Graphics.MeasureString("Laporan Optimal", new Font(DGPrintPrev.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Height - 10);

                            String strDate = DateTime.Now.ToLongDateString() + ", " + DateTime.Now.ToShortTimeString();
                            //Draw Date
                            e.Graphics.DrawString(strDate, new Font(DGPrintPrev.Font, FontStyle.Bold),
                                    Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
                                    e.Graphics.MeasureString(strDate, new Font(DGPrintPrev.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
                                    e.Graphics.MeasureString("", new Font(new Font(DGPrintPrev.Font,
                                    FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - e.Graphics.MeasureString("Laporan Optimal", new Font(DGPrintPrev.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Height - 10);

                            //Draw Columns                 
                            iTopMargin = e.MarginBounds.Top;
                            foreach (DataGridViewColumn GridCol in DGPrintPrev.Columns)
                            {
                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,
                                    new SolidBrush(GridCol.InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                                iCount++;
                            }

                            bNewPage = false;
                            iTopMargin += iHeaderHeight;
                        }
                        iCount = 0;
                        //Draw Columns Contents                
                        foreach (DataGridViewCell Cel in GridRow.Cells)
                        {
                            if (Cel.Value != null)
                            {
                                e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
                                            new SolidBrush(Cel.InheritedStyle.ForeColor),
                                            new RectangleF((int)arrColumnLefts[iCount], (float)iTopMargin,
                                            (int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);
                            }
                            //Drawing Cells Borders 
                            e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
                                    iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));

                            iCount++;
                        }

                    }


                    if (iRow == DGPrintPrev.RowCount - 1)
                    {
                        StopReading = true;
                        break;
                    }
                    iRow++;
                    iTopMargin += iCellHeight;
                }

                //If more lines exist, print another page.
                if (bMorePagesToPrint)
                {
                    e.HasMorePages = true;
                }
                else
                {
                    e.HasMorePages = false;
                }

                if (StopReading)
                {

                    e.Graphics.DrawString("Total :", new Font(DGPrintPrev.Font, FontStyle.Bold),
                                     Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
                                     e.Graphics.MeasureString("Customer Summary", new Font(DGPrintPrev.Font,
                                     FontStyle.Bold), e.MarginBounds.Width).Height + iTopMargin - 50);

                    e.Graphics.DrawString(total + "", new Font(DGPrintPrev.Font, FontStyle.Underline),
                            Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
                            e.Graphics.MeasureString(total + "", new Font(DGPrintPrev.Font,
                            FontStyle.Underline), e.MarginBounds.Width).Width), e.MarginBounds.Top -
                            e.Graphics.MeasureString(total + "", new Font(new Font(DGPrintPrev.Font,
                            FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height + iTopMargin - 50);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void heheToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReportPrint RP = new ReportPrint();
            RP.ShowDialog();
        }
        private int a, b;
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            a = dataGridView1.CurrentCell.RowIndex;
            b = dataGridView1.CurrentCell.ColumnIndex;
        }

        private void NewProject(object sender, EventArgs e)
        {
            dataGridView4.Rows.Clear();
            dataGridView4.Columns.Clear();
            for (int i = 0; i < dataGridView1.RowCount-1; i++)
            {
                dataGridView1.Rows.Clear();
            }
            for (int i = 0; i < dataGridView2.RowCount-1; i++)
            {
                dataGridView2.Rows.Clear();

            }

            

            dataGridView2.Refresh();
            dataGridView1.Refresh();

        }
        private static int idProj;
        private void OpenFromDb(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count != 1)
            {
                DialogResult dlg = MessageBox.Show("Simpan Project?", "Keluar", MessageBoxButtons.YesNoCancel);
                if (dlg == DialogResult.Yes)
                {
                    //simpan
                    FileCmd.TemporarySaveDGV(dataGridView1, dataGridView2, dataGridView4);
                    SaveAs saveAs = new SaveAs();
                    saveAs.Focus();
                    saveAs.ShowDialog();
                    try
                    {
                        FileCmd.SaveAs(dataGridView1, dataGridView2, dataGridView4);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (dlg == DialogResult.No)
                {
                    OpenDB openDB = new OpenDB();
                    openDB.Focus();
                    openDB.ShowDialog();
                    this.Text = openDB.getTextBoxValue();
                    int iItem = Convert.ToInt32(this.Text);
                    FileCmd.OpenProj(dataGridView1, dataGridView2, dataGridView4, iItem);
                    openDB.Close();
                    //utk menu save
                    idProj = iItem;
                }
            }
            else
            {
                OpenDB openDB = new OpenDB();
                openDB.Focus();
                openDB.ShowDialog();
                try
                {
                    this.Text = openDB.getTextBoxValue();
                    int iItem = Convert.ToInt32(this.Text);
                    FileCmd.OpenProj(dataGridView1, dataGridView2, dataGridView4, iItem);
                    openDB.Close();
                    //utk menu save
                    idProj = iItem;
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void SaveToXls(object sender, EventArgs e)
        {

        }

        private void ApplicationStop(object sender, EventArgs e)
        {
            dataGridView1.Enabled = true;
            
            dataGridView2.Enabled = true;
            
            dataGridView4.Enabled = true;

            dataGridView1.ForeColor = Color.Black;
            dataGridView2.ForeColor = Color.Black;
            dataGridView4.ForeColor = Color.Black;
            dataGridView1.BackgroundColor = Color.Gainsboro;
            dataGridView1.BackgroundColor = Color.Gainsboro;
            dataGridView1.BackgroundColor = Color.Gainsboro;

            dataGridView4.DefaultCellStyle.SelectionBackColor = Color.PeachPuff;
            dataGridView4.DefaultCellStyle.SelectionForeColor = Color.Black;
            dataGridView2.DefaultCellStyle.SelectionBackColor = Color.PeachPuff;
            dataGridView2.DefaultCellStyle.SelectionForeColor = Color.Black;
            dataGridView1.DefaultCellStyle.SelectionBackColor = Color.PeachPuff;
            dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;
            dataGridView4.Columns[0].DefaultCellStyle.SelectionBackColor = Color.PeachPuff;
            dataGridView4.Columns[0].DefaultCellStyle.SelectionForeColor = Color.Black;

            toolStripDropDownButton2.Enabled = false;
            toolStripButton1.Enabled = true;
            toolStripButton2.Enabled = false;

        }

        private void aToolStripMenuItem_Click(object sender, EventArgs e)
        {
            printPreviewDialog1.ShowDialog();
        }

        private void bToolStripMenuItem_Click(object sender, EventArgs e)
        {
            printPreviewDialog2.ShowDialog();
        }

        private void printDocument2_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                int i, j;
                List<double[,]> tabel = Mesin.ListRepValue;
                List<string[]> ListBasisVar = Mesin.ListBasisVar;
                string[] ArrNonBasisVar = Mesin.ArrNonBasisVar;
                int jml = tabel.ElementAt(0).GetLength(0)-1;
                double[] Var_Dss_print = new double[jml];
                for (i = 0; i < jml; i++)
                {
                    Var_Dss_print[i] = 0;

                }
                for (int x = 0; x < jml; x++)
                {
                    for (int y = 0; y < jml; y++)
                    {
                        //jika sama
                        if (ListBasisVar.ElementAt(ListBasisVar.Count - 1)[x] == ArrNonBasisVar[y])
                        {
                            Var_Dss_print[y] = tabel.ElementAt(tabel.Count - 1)[x + 1, 0];

                        }
                    }
                }

                #region isi DGV

                //isi DG
                DGprint2.ColumnCount = dataGridView1.RowCount + 1;
                DGprint2.RowCount = tabel.ElementAt(0).GetLength(0) - 1;
                DGPrintPrev.Columns[0].Name = "Batasan";
                //kolom
                for (i = 0; i < dataGridView1.RowCount - 1; i++)
                {
                    DGprint2.Columns[i + 1].Name = dataGridView1.Rows[i].Cells[0].Value + "";
                }

                //baris
                int count = 0;
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //max saja DG2
                    if (Convert.ToString(dataGridView2.Rows[i].Cells[2].Value) != string.Empty && Convert.ToString(dataGridView2.Rows[i].Cells[1].Value) == string.Empty)
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView2.Rows[i].Cells[0].Value;
                        count++;
                    }
                }
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //max campur
                    if (Convert.ToString(dataGridView2.Rows[i].Cells[1].Value) != string.Empty && Convert.ToString(dataGridView2.Rows[i].Cells[2].Value) != string.Empty && Convert.ToString(dataGridView2.Rows[i].Cells[1].Value) != Convert.ToString(dataGridView2.Rows[i].Cells[2].Value))
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView2.Rows[i].Cells[0].Value;
                        count++;
                    }
                }
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //max saja DG1
                    if (Convert.ToString(dataGridView1.Rows[i].Cells[3].Value) != string.Empty && Convert.ToString(dataGridView1.Rows[i].Cells[2].Value) == string.Empty)
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView1.Rows[i].Cells[0].Value;
                        count++;
                    }
                }
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //max campur DG1
                    if (Convert.ToString(dataGridView1.Rows[i].Cells[2].Value) != string.Empty && Convert.ToString(dataGridView1.Rows[i].Cells[3].Value) != string.Empty && Convert.ToString(dataGridView1.Rows[i].Cells[2].Value) != Convert.ToString(dataGridView1.Rows[i].Cells[3].Value))
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView1.Rows[i].Cells[0].Value;
                        count++;
                    }
                }
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //min saja DG2
                    if (Convert.ToString(dataGridView2.Rows[i].Cells[1].Value) != string.Empty && Convert.ToString(dataGridView2.Rows[i].Cells[2].Value) == string.Empty)
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView2.Rows[i].Cells[0].Value;
                        count++;
                    }
                }
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //min campur DG2
                    if (Convert.ToString(dataGridView2.Rows[i].Cells[1].Value) != string.Empty && Convert.ToString(dataGridView2.Rows[i].Cells[2].Value) != string.Empty && Convert.ToString(dataGridView2.Rows[i].Cells[1].Value) != Convert.ToString(dataGridView2.Rows[i].Cells[2].Value))
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView2.Rows[i].Cells[0].Value;
                        count++;
                    }
                }
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //min dg1
                    if (Convert.ToString(dataGridView1.Rows[i].Cells[2].Value) != string.Empty && Convert.ToString(dataGridView1.Rows[i].Cells[3].Value) == string.Empty)
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView1.Rows[i].Cells[0].Value;
                        count++;
                    }
                }
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //min campur DG1
                    if (Convert.ToString(dataGridView1.Rows[i].Cells[2].Value) != string.Empty && Convert.ToString(dataGridView1.Rows[i].Cells[3].Value) != string.Empty && Convert.ToString(dataGridView1.Rows[i].Cells[2].Value) != Convert.ToString(dataGridView1.Rows[i].Cells[3].Value))
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView1.Rows[i].Cells[0].Value;
                        count++;
                    }
                }
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //eq DG2
                    if (Convert.ToString(dataGridView2.Rows[i].Cells[1].Value) != string.Empty && Convert.ToString(dataGridView2.Rows[i].Cells[2].Value) != string.Empty && Convert.ToString(dataGridView2.Rows[i].Cells[1].Value) == Convert.ToString(dataGridView2.Rows[i].Cells[2].Value))
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView2.Rows[i].Cells[0].Value;
                        count++;
                    }
                }
                for (i = 0; i < dataGridView2.RowCount - 1; i++)
                {
                    //eq DG1
                    if (Convert.ToString(dataGridView1.Rows[i].Cells[2].Value) != string.Empty && Convert.ToString(dataGridView1.Rows[i].Cells[3].Value) != string.Empty && Convert.ToString(dataGridView1.Rows[i].Cells[2].Value) == Convert.ToString(dataGridView1.Rows[i].Cells[3].Value))
                    {
                        DGprint2.Rows[count].Cells[0].Value = dataGridView1.Rows[i].Cells[0].Value;
                        count++;
                    }
                }


                for (i = 0; i < tabel.ElementAt(0).GetLength(0) - 1; i++)
                {
                    for (j = 0; j < dataGridView1.RowCount - 1; j++)
                    {
                        DGprint2.Rows[i].Cells[j + 1].Value = tabel.ElementAt(0)[i + 1, j + 1];
                    }
                }
                DGprint2.Columns[dataGridView1.RowCount].Name = "Jumlah";
                for (i = 0; i < tabel.ElementAt(0).GetLength(0) - 1; i++)
                {
                    double sum = 0;
                    for (j = 0; j < dataGridView1.RowCount - 1; j++)
                    {
                        sum = sum + tabel.ElementAt(0)[i + 1, j + 1] * Var_Dss_print[j];
                    }
                    DGprint2.Rows[i].Cells[dataGridView1.RowCount].Value = sum;
                }

                #endregion

                #region beginprint

                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Near;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iRow = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;
                foreach (DataGridViewColumn dgvGridCol in DGPrintPrev.Columns)
                {
                    iTotalWidth += dgvGridCol.Width;
                }

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void printDocument2_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                //Set the left margin
                int iLeftMargin = e.MarginBounds.Left;
                //Set the top margin
                int iTopMargin = e.MarginBounds.Top;
                //Whether more pages have to print or not
                bool bMorePagesToPrint = false;
                int iTmpWidth = 0;
                bool StopReading = false;

                if (bFirstPage)
                {
                    foreach (DataGridViewColumn GridCol in DGprint2.Columns)
                    {

                        iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                                           (double)iTotalWidth * (double)iTotalWidth *
                                           ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                        iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                                    GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                        // Save width and height of headres
                        arrColumnLefts.Add(iLeftMargin);
                        arrColumnWidths.Add(iTmpWidth);
                        iLeftMargin += iTmpWidth;
                    }
                }
                //Loop till all the grid rows not get printed
                while (iRow <= DGprint2.Rows.Count - 1)
                {
                    DataGridViewRow GridRow = DGprint2.Rows[iRow];
                    //Set the cell height
                    iCellHeight = GridRow.Height + 5;
                    int iCount = 0;
                    //Check whether the current page settings allo more rows to print
                    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                    {
                        bNewPage = true;
                        bFirstPage = false;
                        bMorePagesToPrint = true;
                        break;
                    }
                    else
                    {
                        if (bNewPage)
                        {
                            e.Graphics.DrawString("Rincian Sumber Daya", new Font(DGprint2.Font, FontStyle.Bold),
                                    Brushes.Black, e.MarginBounds.Left + 250, e.MarginBounds.Top -
                                    e.Graphics.MeasureString("Rincian Sumber Daya", new Font(DGprint2.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Height - 10);
                            //Draw Header
                            e.Graphics.DrawString("", new Font(DGprint2.Font, FontStyle.Bold),
                                    Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
                                    e.Graphics.MeasureString("", new Font(DGprint2.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Height - e.Graphics.MeasureString("Rincian Sumber Daya", new Font(DGprint2.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Height - 10);

                            String strDate = DateTime.Now.ToShortDateString() + ", " + DateTime.Now.ToShortTimeString();
                            //Draw Date
                            e.Graphics.DrawString(strDate, new Font(DGprint2.Font, FontStyle.Bold),
                                    Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
                                    e.Graphics.MeasureString(strDate, new Font(DGprint2.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
                                    e.Graphics.MeasureString("", new Font(new Font(DGprint2.Font,
                                    FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - e.Graphics.MeasureString("Rincian Sumber Daya", new Font(DGprint2.Font,
                                    FontStyle.Bold), e.MarginBounds.Width).Height - 10);

                            //Draw Columns                 
                            iTopMargin = e.MarginBounds.Top;
                            foreach (DataGridViewColumn GridCol in DGprint2.Columns)
                            {
                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,
                                    new SolidBrush(GridCol.InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                                iCount++;
                            }

                            bNewPage = false;
                            iTopMargin += iHeaderHeight;
                        }
                        iCount = 0;
                        //Draw Columns Contents                
                        foreach (DataGridViewCell Cel in GridRow.Cells)
                        {
                            if (Cel.Value != null)
                            {
                                e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
                                            new SolidBrush(Cel.InheritedStyle.ForeColor),
                                            new RectangleF((int)arrColumnLefts[iCount], (float)iTopMargin,
                                            (int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);
                            }
                            //Drawing Cells Borders 
                            e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
                                    iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));

                            iCount++;
                        }

                    }


                    if (iRow == DGprint2.RowCount - 1)
                    {
                        StopReading = true;
                        break;
                    }
                    iRow++;
                    iTopMargin += iCellHeight;
                }

                //If more lines exist, print another page.
                if (bMorePagesToPrint)
                {
                    e.HasMorePages = true;
                }
                else
                {
                    e.HasMorePages = false;
                }

                if (StopReading)
                {

                    /*e.Graphics.DrawString("Total :", new Font(DGprint2.Font, FontStyle.Bold),
                                     Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
                                     e.Graphics.MeasureString("Customer Summary", new Font(DGprint2.Font,
                                     FontStyle.Bold), e.MarginBounds.Width).Height + iTopMargin - 50);

                    e.Graphics.DrawString(total + "", new Font(DGprint2.Font, FontStyle.Underline),
                            Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
                            e.Graphics.MeasureString(total + "", new Font(DGprint2.Font,
                            FontStyle.Underline), e.MarginBounds.Width).Width), e.MarginBounds.Top -
                            e.Graphics.MeasureString(total + "", new Font(new Font(DGPrintPrev.Font,
                            FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height + iTopMargin - 50);*/
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.EndEdit();
                dataGridView2.EndEdit();
                dataGridView4.EndEdit();
                FileCmd.SaveProj(dataGridView1, dataGridView2, dataGridView4, idProj);
                MessageBox.Show("Disimpan!");
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "Cant Save Project", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void exportToXlsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileCmd.SimpanXls(dataGridView1, dataGridView2);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool isChanged = true; // TO DO
            if (isChanged)
            {
                DialogResult result = MessageBox.Show(
                    "Simpan perubahan?",            // message
                    "Exit",                         // title
                    MessageBoxButtons.YesNoCancel,  // yes - no - cancel
                    MessageBoxIcon.Question,        // type
                    MessageBoxDefaultButton.Button3 // default: button3 (cancel)
                    );
                if (result == DialogResult.Yes)
                {
                    // TO DO
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }

     }
}